package com.centriole.service.workflow.controller;

import com.centriole.common.utils.PaasResult;
import com.centriole.service.workflow.entity.Process;
import com.centriole.service.workflow.service.ActManagerService;
import com.centriole.service.workflow.service.ProcessService;
import com.centriole.service.workflow.util.AjaxResult;
import com.centriole.service.workflow.util.Cache;
import com.centriole.service.workflow.util.CommonUtil;
import com.centriole.service.workflow.util.UserUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/flow")
public class ProcessController {
    @Resource
    private ProcessService processService;
    @Resource
    private ActManagerService actManagerService;

    @RequestMapping("/toFlowList")
    public ModelAndView toFlowList(String type) {
        ModelAndView mv = new ModelAndView("flowpages/processList");
        if (StringUtils.isNotBlank(type)) {
            mv.addObject("type", type);
        }
        return mv;
    }


    @RequestMapping("/startNode")
    public ModelAndView tostartNode(String currentNodeId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("flowpages/startNode");
        mv.addObject("currentNodeId", currentNodeId);
        return mv;
    }

    ;

    @RequestMapping("/userTaskNode")
    public ModelAndView userTaskNode(String currentNodeId, String processId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("flowpages/userTaskNode");
        mv.addObject("currentNodeId", currentNodeId);
        mv.addObject("processId", processId);
        return mv;
    }

    ;

    @RequestMapping("/examineNode")
    public ModelAndView examineNode(String currentNodeId, String processId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("flowpages/examineNode");
        mv.addObject("currentNodeId", currentNodeId);
        mv.addObject("processId", processId);
        return mv;
    }

    ;

    @RequestMapping("/multiTaskOr")
    public ModelAndView multiTaskOr(String currentNodeId, String processId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("flowpages/multiTaskOr");
        mv.addObject("currentNodeId", currentNodeId);
        mv.addObject("processId", processId);
        return mv;
    }

    ;

    @RequestMapping("/childTask")
    public ModelAndView childTask(String childNodeId, String processId) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("flowpages/childTask");
        mv.addObject("childNodeId", childNodeId);
        mv.addObject("processId", processId);
        mv.addObject("currentUser", UserUtils.currentUserInfo().getAccountName());
        mv.addObject("userType", UserUtils.currentUserInfo().getName());
        return mv;
    }

    ;

    @RequestMapping("/process/toEdit")
    public String toFlowList(Model model, String id) {
        if (CommonUtil.isNotEmpty(id)) {
            model.addAttribute("process", JSONObject.fromObject(processService.selectById(id)));
        } else {
            model.addAttribute("process", JSONObject.fromObject(new Process()));
        }
        return "flowpages/processEdit";
    }

    @RequestMapping("/process/processEditBpmn")
    public String processEditBpmn(Model model, String id , String dataInterfaces , String userId ,HttpSession session) {
        //将调用的数据保存起来
        session.setAttribute("dataInterfaces",dataInterfaces);
        if (CommonUtil.isNotEmpty(id)) {
            model.addAttribute("processId", id);
            model.addAttribute("userId",userId);
            model.addAttribute("processJson", JSONObject.fromObject(processService.selectById(id).getBapBpmn()));
        }
        return "flowpages/createFolw";
    }

    ;

    private String getCreatorId(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        return userId == null ? "default" : userId;
    }

    /**
     * 新增流程
     *
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/process/save", method = RequestMethod.POST)
    public AjaxResult save(Process model, HttpServletRequest request) {
        try {
            String userId = getCreatorId(request);
            model.setCreatorId(userId);
            model.setModifierId(userId);
            processService.editProcess(model);
            return AjaxResult.Success("保存成功", model.getPk());
        } catch (Exception e) {
            return AjaxResult.Error(e.getMessage());
        }
    }

    /**
     * 删除流程
     *
     * @param ids
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/process/delete", method = RequestMethod.POST)
    public Object delete(@RequestParam(value = "ids", required = false, defaultValue = "") String[] ids, HttpServletRequest request) {
        try {
            for (String id : ids) {
                processService.logicDelete(id);
            }
            return AjaxResult.Success("删除成功");
        } catch (Exception ce) {
            return AjaxResult.Error(ce.getMessage());
        }
    }

    /**
     * 部署流程
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/process/deploy", method = RequestMethod.POST)
    public Object deploy(String id, HttpServletRequest request) {
        try {
            processService.deploy(id);
            return AjaxResult.Success("部署成功");
        } catch (Exception ce) {
            return AjaxResult.Error(ce.getMessage());
        }
    }

    /**
     * 提供json格式数据
     *
     * @param sortName  排序属性
     * @param sortOrder 排序类型 {asc, desc}
     * @param currPage  当前页
     * @param pageSize  页大小
     * @param request   request
     */
    @ResponseBody
    @RequestMapping("/process/list/json")
    public PaasResult listJson(@RequestParam(value = "sortname", required = false, defaultValue = "") String sortName,
                               @RequestParam(value = "sortorder", required = false, defaultValue = "") String sortOrder,
                               @RequestParam(value = "page", required = false, defaultValue = "") String currPage,
                               @RequestParam(value = "pagesize", required = false, defaultValue = "") String pageSize,
                               @RequestParam(value = "type", required = false, defaultValue = "") String type,
                               HttpServletRequest request) {
        System.out.println(type);

        Map<String, Object> obj = new HashMap<String, Object>();
        List<Process> list = null;
        try {
            list = processService.listAll();
            if (list != null) {
                obj.put("Rows", list);
            }
        } catch (Exception e) {
//            BapLogUtils.logError(JsonConstant.SEARCH_DATA_ERROR, e);
        }
        return  PaasResult.successWithCode0("ok",list);
    }

    @RequestMapping("/process/flowSaveDialog")
    public ModelAndView flowSaveDialog(
            @RequestParam(value = "processId", required = false, defaultValue = "") String processId,
            @RequestParam(value = "isNewVersion", required = false, defaultValue = "") String isNewVersion) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/flow/flowSaveDialog");// 设置页面
        mav.addObject("processId", processId);
        if (!isNewVersion.equals("1")) {
            Process process = processService.selectById(processId);
            Integer version = process.getVersion();
            String viewPageId = "";
            mav.addObject("version", version);
            mav.addObject("viewPageId", viewPageId);
        }
        return mav;
    }

    /**
     * 设置流程实体设计Json数据
     */
    @ResponseBody
    @RequestMapping(value = "/process/set/json")
    public Object setProcessJson(HttpServletRequest request) {
        String processId = request.getParameter("processId");
        //    String versionNote = request.getParameter("versionNote");
        //     String viewPageId = request.getParameter("viewPageId");
        String json = request.getParameter("json");
        //    String isNewVersion = request.getParameter("isNewVersion");
        String userId = getCreatorId(request);
        Process process = processService.selectById(processId);
        process.setBapBpmn(json);
        process.setCreatorId(userId);
        process.setModifierId(userId);
        try {
            //调用Service
            processService.editProcess(process);
            return AjaxResult.Success("成功", process.getPk());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.Error(e.getMessage());
        }
    }

    @RequestMapping(value = "/process/processViewBpmn")
    public ModelAndView viewBpmn(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/flowpages/processViewBpmn");//设置页面
        String instanceId = request.getParameter("instanceId");
        String nodeId = request.getParameter("nodeId");
        mav.addObject("processJson", processService.getBapBpmnByInstanceId(instanceId));

        String nodeCode = processService.getNodeCode(instanceId, nodeId);

        if (CommonUtil.isNotEmpty(nodeCode)) {
            mav.addObject("nodeCode", nodeCode);
        }
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "/process/stop", method = RequestMethod.POST)
    public Object stop(HttpServletRequest request, String key) {
        try {
            processService.stop(key);
            return AjaxResult.Success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.Error(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/process/stopInstance", method = RequestMethod.POST)
    public Object end(HttpServletRequest request, String instanceId) {

        try {
            processService.endActiviti(instanceId);
            return AjaxResult.Success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.Error(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/process/run", method = RequestMethod.POST)
    public Object run(HttpServletRequest request, String key) {
        try {
            processService.run(key);
            return AjaxResult.Success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.Error(e.getMessage());
        }
    }



}
